/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Com.MakeReport_Case;

import Com.Entity.Karyawan;
import Com.Entity.Koneksi;
import Com.Entity.TransaksiGedung;
import Com.Entity.TransaksiKamar;
import SistemPenyewaanKamar.MainController;
import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JMonthChooser;
import com.toedter.calendar.JYearChooser;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRTableModelDataSource;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Yosefina
 */
public class MakeReportController {

    static JasperViewer printView;
    InputStream jasperFile = getClass().getResourceAsStream("/Com/Reports/LaporanBulanan.jasper");
    private static InputStream connURL;

    public MakeReportController() {
    }

    public static InputStream getURL() {
        connURL = new MakeReportController().jasperFile;
        return connURL;
    }

    public static void laporanHarian(JDialog dialog,
            JDateChooser tanggalTransaksiChooser, JTable kamarTable, JTable gedungTable,
            JLabel vvipTotalIncomeLabel, JLabel vipTotalIncomeLabel, JLabel commonTotalIncomeLabel, JLabel kamarTotalIncomeLabel,
            JLabel ballRoomTotalIncomeLabel, JLabel meetingRoomTotalIncomeLabel, JLabel gedungTotalIncomeLabel) {
        if (tanggalTransaksiChooser.getDate() != null) {
            try {
                DailyReportKamar(tanggalTransaksiChooser, kamarTable);

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, ex.getMessage());
            }
            if (kamarTable.getValueAt(0, 0) != null) {
                totalPendapatanHarianKamar(kamarTable, vvipTotalIncomeLabel, vipTotalIncomeLabel, commonTotalIncomeLabel, kamarTotalIncomeLabel);
            } else {
                vvipTotalIncomeLabel.setText("Rp0,00");
                vipTotalIncomeLabel.setText("Rp0,00");
                commonTotalIncomeLabel.setText("Rp0,00");
                kamarTotalIncomeLabel.setText("Rp0,00");
            }
            try {
                DailyReportGedung(tanggalTransaksiChooser, gedungTable);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, ex.getMessage());
            }
            if (gedungTable.getValueAt(0, 0) != null) {
                totalPendapatanHarianGedung(gedungTable, ballRoomTotalIncomeLabel, meetingRoomTotalIncomeLabel, gedungTotalIncomeLabel);
            } else {
                ballRoomTotalIncomeLabel.setText("Rp0,00");
                meetingRoomTotalIncomeLabel.setText("Rp0,00");
                gedungTotalIncomeLabel.setText("Rp0,00");
            }
        } else {
            JOptionPane.showMessageDialog(dialog, "Tanggal belum dipilih "
                    + "atau format penulisan salah"
                    + "\n format penulisan tanggal: dd MMM yy");
        }
    }

    private static void DailyReportKamar(JDateChooser tglTransaksi, JTable kamarTabel) throws Exception {
        TableCellRenderer kanan = new RenderingKanan();
        if (tglTransaksi.getDate() != null) {
            List<TransaksiKamar> kamar = TransaksiKamar.getKoneksiKontrol().getDailyReportKamar(tglTransaksi.getDate());
            DailyReportKamarTableModel model = new DailyReportKamarTableModel(kamar);
            if (kamar.isEmpty()) {
                kamarTabel.setModel(new javax.swing.table.DefaultTableModel(
                        new Object[][]{
                            {null, null, null, null, null},
                            {null, null, null, null, null},
                            {null, null, null, null, null},
                            {null, null, null, null, null}
                        },
                        new String[]{
                            "NO CHECKIN", "NOMOR KAMAR", "TANGGAL MASUK", "TANGGAL KELUAR", "TOTAL HARGA SEWA"
                        }));
                throw new Exception("Tidak ada transaksi kamar yang terjadi "
                        + "pada hari yang dipilih");
            } else {
                kamarTabel.setModel(model);
                kamarTabel.getColumnModel().getColumn(4).setCellRenderer(kanan);
            }
        }
    }

    private static void DailyReportGedung(JDateChooser tanggalTransaksiGedung, JTable gedungTabel) throws Exception {
        TableCellRenderer kanan = new RenderingKanan();
        if (tanggalTransaksiGedung.getDate() != null) {
            List<TransaksiGedung> gedung = TransaksiGedung.getKoneksiKontrol().getDailyReportGedung(tanggalTransaksiGedung.getDate());
            DailyReportGedungTableModel model2 = new DailyReportGedungTableModel(gedung);
            if (gedung.isEmpty()) {
                gedungTabel.setModel(new javax.swing.table.DefaultTableModel(
                        new Object[][]{
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null}
                        },
                        new String[]{
                            "NO TRANSAKSI", "TANGGAL SEWA", "JENIS GEDUNG", "JAM SEWA", "JAM KELUAR", "TOTAL TAGIHAN"
                        }));
                throw new Exception("Tidak ada transaksi gedung yang terjadi "
                        + "pada hari yang dipilih");
            } else {
                gedungTabel.setModel(model2);
                gedungTabel.getColumnModel().getColumn(5).setCellRenderer(kanan);
            }
        }

    }

    private static void totalPendapatanHarianKamar(JTable kamarTabel, JLabel vip, JLabel vvip, JLabel common,
            JLabel totalPemasukan) {
        long totalVip = 0;
        long totalVvip = 0;
        long totalCommon = 0;

        for (int i = 0; i < kamarTabel.getRowCount(); i++) {
            String jenis = kamarTabel.getValueAt(i, 1).toString();
            long a = Long.parseLong(kamarTabel.getValueAt(i, 4).toString().substring(2).replace(".", "").replace(",00", ""));
            if (jenis.toLowerCase().toString().substring(0, 1).matches("2")) {
                totalVvip = totalVvip + a;
            } else if (jenis.toLowerCase().toString().substring(0, 1).matches("3")) {
                totalVip = totalVip + a;
            } else {
                totalCommon = totalCommon + a;
            }
        }
        NumberFormat number = NumberFormat.getCurrencyInstance();
        vvip.setText(number.format(totalVvip));
        vip.setText(number.format(totalVip));
        common.setText(number.format(totalCommon));
        totalPemasukan.setText(number.format(totalVvip + totalVip + totalCommon));
    }

    private static void totalPendapatanHarianGedung(JTable gedungTable, JLabel ballRoomTotalIncomeLabel,
            JLabel meetingRoomTotalIncomeLabel, JLabel gedungTotalIncomeLabel) {
        long totalBallRom = 0;
        long totalMeetingRoom = 0;
        for (int i = 0; i < gedungTable.getRowCount(); i++) {
            String jenis = gedungTable.getValueAt(i, 2).toString().toUpperCase().replace(" ", "");
            if (jenis.matches("BALLROOM")) {
                totalBallRom = totalBallRom + Long.parseLong(gedungTable.getValueAt(i, 5).toString().substring(2).replace(".", "").replace(",00", ""));
            } else {
                totalMeetingRoom = totalMeetingRoom + Long.parseLong(gedungTable.getValueAt(i, 5).toString().substring(2).replace(".", "").replace(",00", ""));
            }
        }
        NumberFormat formatNilai = NumberFormat.getCurrencyInstance();
        ballRoomTotalIncomeLabel.setText(formatNilai.format(totalBallRom));
        meetingRoomTotalIncomeLabel.setText(formatNilai.format(totalMeetingRoom));
        gedungTotalIncomeLabel.setText(formatNilai.format(totalBallRom + totalMeetingRoom));
    }

    public static void monthlyReport(JButton cetakButton, JMonthChooser jMonthChooser, JYearChooser jYearChooser, JTable monthlyReportTable,
            JLabel totalKamarLabel, JLabel totalGedungLabel, JLabel totalGedungKamarLabel)
            throws SQLException, IOException, Exception {

        String bulan = String.valueOf(jMonthChooser.getMonth() + 1);
        String tahun = String.valueOf(jYearChooser.getYear());
        String tanggal = bulan + "-" + tahun;
        String sqlTanggal = "select to_char(a.tanggalkeluar,'dd-MM-yyyy'),to_char(b.tanggalsewa,'dd-MM-yyyy') "
                + "from transaksikamar a full outer join transaksigedung b on a.tanggalkeluar = b.tanggalsewa "
                + "where to_char(a.tanggalkeluar,'MM-yyyy')=(?)  "
                + "or to_char(b.tanggalsewa,'MM-yyyy')=(?) group by a.tanggalkeluar,b.tanggalsewa";
        Connection koneksi = Koneksi.getDBConnection();
        PreparedStatement psmt = koneksi.prepareStatement(sqlTanggal);
        psmt.setObject(1, tanggal);
        psmt.setObject(2, tanggal);
        ResultSet rset = psmt.executeQuery();
        int index = 0;
        int total = 0;
        LinkedList tanggalCount = new LinkedList();
        while (rset.next()) {
            total++;
            Object a = null, b = null;
            if (rset.getObject(1) != null || rset.getObject(2) != null) {
                if (rset.getObject(1) != null) {
                    a = String.valueOf(rset.getObject(1));
                }
                if (rset.getObject(2) != null) {
                    b = String.valueOf(rset.getObject(2));
                }
                if (a == b) {
                    tanggalCount.add(String.valueOf(a));
                } else if (a != null) {
                    tanggalCount.add(String.valueOf(a));
                } else {
                    tanggalCount.add(String.valueOf(b));
                }
                index++;
            }
        }
        Object[] c = tanggalCount.toArray();
        Arrays.sort(c);
        LinkedList dataTransaksi = new LinkedList();
        String sqlData = "select "
                + "(select sum(totaltagihan) from transaksikamar where to_char(tanggalkeluar,'dd-MM-yyyy')=(?)),"
                + "(select sum(totaltagihan) from transaksigedung where to_char(tanggalsewa,'dd-MM-yyyy')=(?)) "
                + "from dual";
        for (int i = 0; i < c.length; i++) {
            String tanggalTransaksi = String.valueOf(c[i]);
            PreparedStatement psmt2 = koneksi.prepareStatement(sqlData);
            psmt2.setObject(1, tanggalTransaksi);
            psmt2.setObject(2, tanggalTransaksi);
            ResultSet rset2 = psmt2.executeQuery();
            while (rset2.next()) {
                long totalPendapatanKamar = rset2.getLong(1);
                long totalPendapatanGedung = rset2.getLong(2);
                dataTransaksi.add(tanggalTransaksi);
                dataTransaksi.add(totalPendapatanKamar);
                dataTransaksi.add(totalPendapatanGedung);
                dataTransaksi.add(totalPendapatanKamar + totalPendapatanGedung);
            }
        }

        Object[] dataTrans = dataTransaksi.toArray();
        String[] kolom = {"Tanggal", "Total Pendapatan Sewa Kamar", "Total Pendapatan Sewa Gedung", "Total Pendapatan Transaksi"};
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(kolom);
        if (dataTrans.length == 0) {
            monthlyReportTable.setModel(new javax.swing.table.DefaultTableModel(
                    new Object[][]{
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null}
                    },
                    new String[]{"Tanggal", "Total Pendapatan Sewa Kamar", "Total Pendapatan Sewa Gedung", "Total Pendapatan Transaksi"}));
            totalKamarLabel.setText("RP 0,00");
            totalGedungLabel.setText("RP 0,00");
            totalGedungKamarLabel.setText("RP 0,00");
            cetakButton.setEnabled(false);
            throw new Exception("Tidak ada data pada bulan dan tahun masukan");
        } else {
            NumberFormat numFormat = NumberFormat.getCurrencyInstance();
            while (!dataTransaksi.isEmpty()) {
                String[] data = new String[4];
                for (int i = 0; i < 4; i++) {
                    if (i > 0) {
                        Object temporary = dataTransaksi.remove();
                        if (String.valueOf(temporary).matches("0")) {
                            data[i] = "Rp0,00";
                        } else {
                            data[i] = numFormat.format(temporary);
                        }
                    } else {
                        data[i] = String.valueOf(dataTransaksi.remove());
                    }
                }
                model.addRow(data);
            }
            monthlyReportTable.setModel(model);
            TableCellRenderer kanan = new RenderingKanan();
            monthlyReportTable.getColumnModel().getColumn(1).setCellRenderer(kanan);
            monthlyReportTable.getColumnModel().getColumn(2).setCellRenderer(kanan);
            monthlyReportTable.getColumnModel().getColumn(3).setCellRenderer(kanan);
            long totalkamar = 0;
            long totalgedung = 0;
            long totaltransaksi = 0;
            for (int i = 0; i < monthlyReportTable.getRowCount(); i++) {
                String totKamar, totGedung;
                String totTransaksi = monthlyReportTable.getValueAt(i, 3).toString().substring(2).replace(".", "").replace(",00", "");
                totKamar = monthlyReportTable.getValueAt(i, 1).toString().substring(2).replace(".", "").replace(",00", "");
                totGedung = monthlyReportTable.getValueAt(i, 2).toString().substring(2).replace(".", "").replace(",00", "");
                totalkamar = totalkamar + (Long.parseLong(totKamar));
                totalgedung = totalgedung + (Long.parseLong(totGedung));
                totaltransaksi = totaltransaksi + (Long.parseLong(totTransaksi));
            }
            totalKamarLabel.setText(numFormat.format(totalkamar));
            totalGedungLabel.setText(numFormat.format(totalgedung));
            totalGedungKamarLabel.setText(numFormat.format(totaltransaksi));
            cetakButton.setEnabled(true);
        }
    }

    public static void cetakLaporan(JTable monthlyReportTable,
            JLabel totalKamarLabel, JLabel totalGedungLabel, JLabel totalGedungKamarLabel) {
        try {
            String nama = null, idKaryawan = null, jabatan = null;
            List<Karyawan> kTest = Karyawan.getKoneksiKontrol().getDataKaryawan(Karyawan.getusrID());
            for (Karyawan k : kTest) {
                nama = k.getLastName() + ", " + k.getFirstName();
                idKaryawan = k.getUsername();
                jabatan = k.getJabatan();
            }
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("Total Gedung", totalGedungLabel.getText());
            params.put("Total kamar", totalKamarLabel.getText());
            params.put("Total Transaksi", totalGedungKamarLabel.getText());
            params.put("idkaryawan", idKaryawan);
            params.put("jabatankaryawan", jabatan);
            params.put("lastnamekaryawan", nama);
            JasperPrint jasperPrint = JasperFillManager.fillReport(MakeReportController.getURL(),
                    params, new JRTableModelDataSource(monthlyReportTable.getModel()));
            if (printView == null) {
                printView = new JasperViewer(jasperPrint, false);
                printView.addWindowListener(new WindowAdapter() {

                    @Override
                    public void windowClosing(WindowEvent e) {
                        printView.dispose();
                        printView = null;
                    }
                });
            }
            printView.show(true);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Reports Error  " + e.toString());
        }
    }

    public static void back(JDialog dialog, JButton cetakButton, JTable monthlyReportTable,
            JLabel totalKamarLabel, JLabel totalGedungLabel, JLabel totalGedungKamarLabel,
            JMonthChooser bulanChooser, JYearChooser tahunChooser) {
        dialog.dispose();
        monthlyReportTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                },
                new String[]{"Tanggal", "Total Pendapatan Sewa Kamar",
                    "Total Pendapatan Sewa Gedung", "Total Pendapatan Transaksi"}));
        totalKamarLabel.setText("RP 0,00");
        totalGedungLabel.setText("RP 0,00");
        totalGedungKamarLabel.setText("RP 0,00");
        Date date = new Date();
        bulanChooser.setMonth(date.getMonth());
        tahunChooser.setYear(date.getYear()+1900);
        cetakButton.setEnabled(false);
        cetakButton.setEnabled(false);
        MakeReportController.printView = null;
        MainController.getFrame().setVisible(true);
    }
}
